package cn.hxzy.user.servlet;

import cn.hxzy.user.service.RoleService;
import cn.hxzy.user.service.UserService;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/roleDelete/*")
public class RoleDeleteServlet extends HttpServlet {
    private UserService userService = new UserService();
    private RoleService roleService = new RoleService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println(req.getRequestURI());
        String[] split = req.getRequestURI().split("/");
        System.out.println(split[split.length - 1]);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter writer = resp.getWriter();
        try {
            String id = req.getParameter("id");
            if (id != null && id != "") {
                int count = userService.countByRoleId(Integer.parseInt(id));
                Map map = new HashMap();
                if (count == 0) {
                    roleService.deleteById(Integer.parseInt(id));
                    map.put("code", 200);
                    map.put("msg", "操作成功");
                } else {
                    map.put("code", 300);
                    map.put("msg", "角色被用户使用，不能删除");
                }
                writer.write(JSON.toJSONString(map));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
